#include "register.h"
#include "ui_register.h"
#include <QMessageBox>
#include <QTcpSocket>
#include <QDebug>
#include "tools.h"

//注册页面
Register::Register(QTcpSocket *socket,QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Register)
    , socket(socket)
{
    ui->setupUi(this);
}

Register::~Register()
{
    delete ui;
}

//点击注册按钮
//从界面获取账号信息，进行格式判断，发送给服务端，新建用户
//注册成功则自动关闭注册页面
void Register::on_pushButton_reg_clicked()
{
    QString username=ui->lineEdit_username->text();
    QString password=ui->lineEdit_password->text();
    QString gender=ui->comboBox_gender->currentText();
    int age = ui->lineEdit_age->text().toInt();
    QString phone=ui->lineEdit_phone->text();
    qDebug()<<"注册用户："
            <<"username: "<<username
            <<"password: "<<password
            <<"gender: "<<gender
            <<"age: "<<age
            <<"phone: "<<phone;
    if(!usernameIsTrue(username)||!passwordIsTrue(password)){
        QMessageBox::warning(this, "注册失败", "用户名或密码格式错误！");
        return;
    }
    //判断电话号码
    if(!phoneIsTrue(phone)){
        QMessageBox::warning(this, "注册失败", "电话号码格式错误！");
        return;
    }


    //如果正确，发送请求，关闭注册页面
    sendDatabase(socket,Database,Insert,table_user);
    User user;
    user.setUsername(username);
    user.setPassword(password);
    user.setGender(gender);
    user.setAge(age);
    user.setPhone(phone);
    sendUserData(socket,user);
    //等待1秒
    waitForTimeout(1000);
    QByteArray data;
    if (socket->bytesAvailable() > 0) {
        // 有数据可以读取
        data = socket->readAll();
        qDebug()<<"注册页面--读取返回信息: "<<data;
    }else{
        qDebug()<<"注册页面--没有返回信息";
        return;
    }
    QDataStream in(data);
    in.setByteOrder(QDataStream::LittleEndian);
    QString res;
    in>>res;
    QMessageBox::warning(this, "注册信息", res);
    this->close();
}

